package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @author amanda
 * @Description Redis的封装工具类
 */
@Component
@Slf4j
public class CacheClient {
    private final StringRedisTemplate stringRedisTemplate;
    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }
    /**
     * 缓存穿透
     * @param id
     * @return
     */
    public <R,ID> R getWithPassThrough(String keyField, ID id, Class<R> type,
                                       Function<ID,R> dbFallback,Long time,TimeUnit unit) {
        // 从redis查询缓存
        String key = keyField + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        // 判断是否存在
        if (StrUtil.isNotBlank(json)) {
            // 存在直接返回
            return JSONUtil.toBean(json,type);
        }
        if (json != null) {
            return null;
        }
        // 不存在则查询数据库
        R r = dbFallback.apply(id);
        // 数据库中不存在信息，返回错误
        if (r == null) {
            stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        // 数据库存在信息，写入redis返回
        this.set(key,r,time,unit);
        return r;
    }
    public void setWithLoginExpire(String key,Object value,Long time,TimeUnit unit) {
        // 设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        redisData.setData(value);
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    /**
     * 逻辑过期解决缓存击穿
     * @param id
     * @return
     */
    public <R,ID> R getWithLoginExpire(String keyField,ID id,Class<R> type,
                                       Function<ID,R> dbFallback,Long time,TimeUnit unit) {
        String key = keyField + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(json)) {
            return null;
        }
        // 命中，先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())) {
            // 未过期，直接返回
            return r;
        }
        // 过期。缓存重建
        // 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY+id;
        Boolean aBoolean = tryLock(lockKey);
        // 判断是否获取锁成功
        if (aBoolean) {
            // 成功，开启独立线程
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    R r1 = dbFallback.apply(id);
                    this.setWithLoginExpire(key,r1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    tryDisLock(lockKey);
                }
            });
        }
        // 返回信息
        return r;
    }
    /**
     * 获取互斥锁
     * @param key
     * @return
     */
    private Boolean tryLock(String key) {
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }
    /**
     * 释放锁
     * @param key
     */
    private void tryDisLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
